package cn.t.xsmart.lifecycledemo;

import android.arch.lifecycle.LifecycleOwner;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements LifecycleOwner, View.OnClickListener {

    private String TAG = getClass().getSimpleName();
    private UserModel userModel;
    private TextView mTvChangeDate, mTvChangeDateList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getLifecycle().addObserver(new Dosomething(this, getLifecycle()));
        mTvChangeDate = findViewById(R.id.mTvChangeDate);
        mTvChangeDateList = findViewById(R.id.mTvChangeDateList);
        mTvChangeDate.setOnClickListener(this);
        mTvChangeDateList.setOnClickListener(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        userModel = ViewModelProviders.of(this).get(UserModel.class);
        userModel.getCurrUser().observe(this, new Observer<User>() {
            @Override
            public void onChanged(@Nullable User user) {
                Log.i(TAG, "onChanged: " + user.toString());
            }
        });

        userModel.getUserList().observe(this, new Observer<List<User>>() {
            @Override
            public void onChanged(@Nullable List<User> users) {
                for (User user : users) {
                    Log.i(TAG, "onChanged:--> " + user.toString());
                }
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.mTvChangeDate:
                userModel.getCurrUser().setValue(new User("10", "Hejingzhou", "1230"));
                break;
            case R.id.mTvChangeDateList:
                List<User> userList = new ArrayList<>();
                for (int i = 0; i < 14; i++) {
                    userList.add(new User("22", "44", "55"));
                }
                userModel.getUserList().setValue(userList);
                break;
            default:
                break;
        }
    }
}
